package com.alameda.exception;

import com.alameda.result.Result;
import com.alameda.result.ResultEnum;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.alameda.base.constant.ProjectConstant.TRACE_ID;

/**
 * 前端返回值异常处理类
 *
 * @author Lv
 * @date 2024/2/19
 */
@RestControllerAdvice
public class ResultExceptionHandler {
    /**
     * 全局异常捕捉
     *
     * @param businessException 业务异常
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<?> exception(BusinessException businessException) {
        // 获取错误枚举
        ResultEnum resultEnum = businessException.getResultEnum();
        // 获取详细错误信息
        String errorMessage = businessException.getMessage();
        // 控制台输出错误信息
        businessException.printStackTrace();
        // 将错误信息以固定格式返回给前端
        Result<?> result = (errorMessage == null || "".equals(errorMessage)) ? Result.failed(resultEnum) : Result.failed(resultEnum, errorMessage);
        // 封装链路id
        result.setTraceId(MDC.get(TRACE_ID));
        // 释放内存
        MDC.remove(TRACE_ID);
        return result;
    }
}
